import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ATable, { ATableColumn, SearchToolBarProps } from '@apulis/table';
import type { ActionType } from '@apulis/table/lib/typing';
import { flowRequest } from '@/utils/request';
import trans from '@/utils/translate';
import { Link } from 'umi';
import { Button, Card, Modal, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { listAPI } from './service';
import { getStatus } from '../const';
import format from '@/utils/format';
import { deleteTask, updateTask } from './service';
const CentralInference: React.FC = (props) => {

  const tableRef = useRef<ActionType>();
  const handleRemoveApplication = (id: string) => {
    Modal.confirm({
      centered: true,
      closable: true,
      icon: <ExclamationCircleOutlined />,
      maskClosable: true,
      okType: 'danger',
      okText: '确认',
      cancelText: '取消',
      width: '30%',
      title: <div style={{ fontWeight: 'bold' }}>{trans('deployOnline.centralInference.delete.title')}</div>,
      content: <div>{trans('deployOnline.centralInference.delete.content')}</div>,
      onOk: async () => {
        deleteTask(id).then((res) => {
          if (res.code === 0) {
            message.success(trans('deployOnline.centralInference.delete.success'));
            tableRef.current?.reload();
          }
        });
      },
      cancelButtonProps: {},
      onCancel: () => {},
    });
  };
  function updateTaskType(id: string, cmd: string) {
    updateTask(id, { cmd: cmd }).then((res) => {
      console.log(res);
      if (res.code == 0) {
        message.success('操作成功');
        tableRef.current?.reload();
      }
    });
  }
  // function onSearch(e) {
  //   console.log('搜索', e);
  //   setSearchText(e);
  //   tableRef.current.reload();
  // }
  const columns: ATableColumn[] = [
    {
      title: trans('deployOnline.centralInference.serviceName'),
      dataIndex: 'name',
      render: (text, record) =>
        <Link to={`/deploy-online/central-inference/detail?appId=${record.id}&appName=${text}`}>
          {text}
        </Link>
    },
    {
      title: trans('deployOnline.centralInference.serviceStatus'),
      dataIndex: 'status',
      render: (text) => getStatus(text)
    },
    {
      title: trans('deployOnline.centralInference.modelName'),
      dataIndex: 'name',
      render: (text, record) => {
        record = record.models.length > 0 ? record.models[0] : {};
        return record.name;
      },
    },

    {
      title: trans('deployOnline.centralInference.modelVersion'),
      dataIndex: 'versionId',
      render: (text, record) => {
        record = record.models.length > 0 ? record.models[0] : {};
        return record.version;
      },
    },
    {
      title: trans('deployOnline.centralInference.createdAt'),
      dataIndex: 'createdAt',
      render(text) {
        return <span>{format(text)}</span>;
      },
      sorter: (a, b) => a.createdAt - b.createdAt,
    },
    {
      title: trans('deployOnline.centralInference.operation'),
      render(text, record) {
        return (
          <>
            <Link
              to={`/deploy-online/central-inference/add?appId=${record.id}&appName=${record.name}&edit=true`}
              style={{ marginRight: '20px' }}
            >
              {trans('deployOnline.centralInference.copy')}
            </Link>
            {record.status === 'running' && (
              <Link
                to={`/deploy-online/central-inference/detail?appId=${record.id}&appName=${record.name}`}
                style={{ marginRight: '20px' }}
              >
                {trans('deployOnline.centralInference.forecast')}
              </Link>
            )}

            {record.status == 'stop' && (
              <span
                style={{ marginRight: '20px', cursor: 'pointer' }}
                onClick={() => {
                  updateTaskType(record.id, 'start');
                }}
              >
                {trans('deployOnline.centralInference.start')}
              </span>
            )}
            {(record.status === 'running' || record.status === 'scheduling') && (
              <span
                style={{ marginRight: '20px', cursor: 'pointer' }}
                onClick={() => {
                  updateTaskType(record.id, 'stop');
                }}
              >
                {trans('deployOnline.centralInference.stop')}
              </span>
            )}
            {(record.status !== 'terminating' && record.status !== 'scheduling') && (<a style={{ color: 'red' }} onClick={() => handleRemoveApplication(record.id)}>
              {trans('common.delete')}
            </a>)}
          </>
        );
      },
    }
  ];
  const searchList: SearchToolBarProps[] = [
    {
      type: 'select',
      name: 'status',
      label: '状态',
      selectOptions: [
        { label: '模型转换中', value: 'model-transform' },
        { label: '调度中', value: 'scheduling' },
        { label: '运行中', value: 'running' },
        { label: '已停止', value: 'stop' },
        { label: '失败', value: 'error' },
        { label: '停止中', value: 'terminating' },
      ],
      placeholder: '请选择状态',
      selectProps: { allowClear: true }
    },
    {
      type: 'input',
      name: 'name',
      label: '模型名称',
      placeholder: '请输入服务名称',
      inputProps: { allowClear: true },
    }
  ]

  return (
    <PageContainer>
      <Card>
        <ATable
          actionRef={tableRef}
          request={flowRequest}
          dataSourceAPIPath={listAPI}
          columns={columns}
          rowKey='name'
          searchToolBar={searchList}
          leftToolBar={(
            <Link to='/deploy-online/central-inference/add'>
              <Button type='primary'>{trans('deployOnline.centralInference.addCentralInference')}</Button>
            </Link>
          )}
        ></ATable>
      </Card>
    </PageContainer>
  )
}

export default CentralInference;
